﻿using MixingStation.LTWebService;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MixingStation
{
    public partial class UnPurchaseWeightInfoForm : Form
    {
        //当前选择的物料编码
        private string m_MaterialCode ="";
        //当前选择的供应商编码
        private string m_SupplierCode ="";
        //当前选择的物产地编码
        private string m_PlaceCode = "";
        //当前选择的流向编码
        private string m_DirectionCode = "";
        //当前选择的状态（）
        private int m_Status = 0;
        //当前选择的打印状态
        private int m_Printed = 0;
        //当前选择的补录状态
        private int m_Record = 0;
        //绑定DataTable
        private DataTable m_BindDT = null;

        private List<materialWS> m_MaterialList = new List<materialWS>();
        public List<materialWS> MaterialList
        {
            set { m_MaterialList = value; }
        }
        private List<supplierWS> m_SupplierList = new List<supplierWS>();
        public List<supplierWS> SupplierList
        {
            set { m_SupplierList = value; }
        }

        private List<placeWS> m_PlaceList = new List<placeWS>();
        public List<placeWS> PlaceList
        {
            set { m_PlaceList = value; }
        }

        private List<DirectionInfo> m_DirectionList = new List<DirectionInfo>();
        public List<DirectionInfo> DirectionList
        {
            set { m_DirectionList = value; }
        }

        private string m_CurrentUser = "";
        public string CurrentUser
        {
            get { return m_CurrentUser; }
            set { m_CurrentUser = value; }
        }

        private string m_Password = "";
        public string Password
        {
            get { return m_Password; }
            set { m_Password = value; }
        }

        public UnPurchaseWeightInfoForm()
        {
            InitializeComponent();
        }

        private void WeightInfoForm_Load(object sender, EventArgs e)
        {
            this.Size = Screen.GetWorkingArea(this).Size;
            this.Location = new Point(0, 0);

            InitBinDT();
            InitCmbMaterial();
            InitCmbSupplier();
            InitCmbPlace();
            InitCmbDirection();
            InitCmbPrinted();
            InitCmbStatus();
            InitDateTime();
            InitCmbIsReturn();
        }

        #region 初始化
        //初始化物料下拉框
        private void InitCmbMaterial()
        {
            try
            {
                if (m_MaterialList == null || m_MaterialList.Count == 0)
                    return;
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "", Value = "" });
                foreach (materialWS material in m_MaterialList)
                    list.Add(new DataInfo { Id = material.code.ToString(), Value = material.name });
                cmbMaterial.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbMaterial.Properties.Items.Add(item);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化物料下拉框异常：" + ex.ToString());
            }
        }

        //初始化供应商下拉框
        private void InitCmbSupplier()
        {
            try
            {
                if (m_SupplierList == null || m_SupplierList.Count == 0)
                    return;
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "", Value = "" });
                foreach (supplierWS supplier in m_SupplierList)
                    list.Add(new DataInfo { Id = supplier.code.ToString(), Value = supplier.name });
                cmbSupplier.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbSupplier.Properties.Items.Add(item);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化供应商下拉框异常：" + ex.ToString());
            }
        }

        //初始化产地下拉框
        private void InitCmbPlace()
        {
            try
            {
                if (m_PlaceList == null || m_PlaceList.Count == 0)
                    return;
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "", Value = "" });
                foreach (placeWS place in m_PlaceList)
                    list.Add(new DataInfo { Id = place.id.ToString(), Value = place.name });
                cmbPlace.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbPlace.Properties.Items.Add(item);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化产地下拉框异常：" + ex.ToString());
            }
        }

        //初始化流向下拉框
        private void InitCmbDirection()
        {
            try
            {
                if (m_DirectionList == null || m_DirectionList.Count == 0)
                    return;
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "", Value = "" });
                foreach (DirectionInfo direction in m_DirectionList)
                    list.Add(new DataInfo { Id = direction.Code.ToString(), Value = direction.Name });
                cmbDirection.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbDirection.Properties.Items.Add(item);
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化流向下拉框异常：" + ex.ToString());
            }
        }

        //初始化是否补录下拉框
        private void InitCmbIsReturn()
        {
            try
            {
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "0", Value = "所有" });
                list.Add(new DataInfo { Id = "1", Value = "否" });
                list.Add(new DataInfo { Id = "2", Value = "是" });
                cmbIsReturn.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbIsReturn.Properties.Items.Add(item);
                cmbIsReturn.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化是否补录下拉框异常：" + ex.ToString());
            }
        }

        //初始化是否打印下拉框
        private void InitCmbPrinted()
        {
            try
            {
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "0", Value = "所有" });
                list.Add(new DataInfo { Id = "1", Value = "未打印" });
                list.Add(new DataInfo { Id = "2", Value = "已打印" });
                cmbPrinted.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbPrinted.Properties.Items.Add(item);
                cmbPrinted.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化打印状态下拉框异常：" + ex.ToString());
            }
        }

        //初始化状态下拉框
        private void InitCmbStatus()
        {
            try
            {
                var list = new List<DataInfo>();
                list.Add(new DataInfo { Id = "0", Value = "全部" });
                list.Add(new DataInfo { Id = "1", Value = "未完结" });
                list.Add(new DataInfo { Id = "2", Value = "完结" });

                cmbStatus.Properties.Items.Clear();
                foreach (DataInfo item in list)
                    cmbStatus.Properties.Items.Add(item);
                cmbStatus.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                LogHelper.error("初始化状态下拉框异常：" + ex.ToString());
            }
        }

        //初始化时间
        private void InitDateTime()
        {
            DateTime current = DateTime.Now;
            fromFirstTime.EditValue = new DateTime(current.Year, current.Month, current.Day, 0, 0, 0);
            toFirstTime.EditValue = new DateTime(current.Year, current.Month, current.Day, 23, 59, 59);
            fromLastTime.EditValue = new DateTime(current.Year, current.Month, current.Day, 0, 0, 0);
            toLastTime.EditValue = new DateTime(current.Year, current.Month, current.Day, 23, 59, 59);
        }

        //初始化绑定的DT
        private void InitBinDT()
        {
            m_BindDT = new DataTable();
            m_BindDT.Columns.Add("SystemId");
            m_BindDT.Columns.Add("CarCode");
            m_BindDT.Columns.Add("MaterialCode");
            m_BindDT.Columns.Add("Material");
            m_BindDT.Columns.Add("SupplierCode");
            m_BindDT.Columns.Add("Supplier");
            m_BindDT.Columns.Add("PlaceCode");
            m_BindDT.Columns.Add("Place");
            m_BindDT.Columns.Add("DirectionCode");
            m_BindDT.Columns.Add("Direction");
            m_BindDT.Columns.Add("ReceiveCode");
            m_BindDT.Columns.Add("ReceiveName");
            m_BindDT.Columns.Add("TempWeight");
            m_BindDT.Columns.Add("GrossWeight");
            m_BindDT.Columns.Add("Tareweight");
            m_BindDT.Columns.Add("BuckleWeight");
            m_BindDT.Columns.Add("BuckleReasons");
            m_BindDT.Columns.Add("NetWeight");
            m_BindDT.Columns.Add("FirstWeightTime");
            m_BindDT.Columns.Add("FirstWeightMan");
            m_BindDT.Columns.Add("LastWeightTime");
            m_BindDT.Columns.Add("LastWeightMan");
            m_BindDT.Columns.Add("Status");
            m_BindDT.Columns.Add("Printed");
            m_BindDT.Columns.Add("IsRecord");
            m_BindDT.Columns.Add("Remark");
        }
        #endregion

        #region 按钮事件
        private void btnSearch_Click(object sender, EventArgs e)
        {
            Search();
        }

        //数据补录
        private void btnAdd_Click(object sender, EventArgs e)
        {
            //管理员权限进行修改
            AdminConfirmForm adminForm = new AdminConfirmForm();
            if (adminForm.ShowDialog() != DialogResult.OK)
                return;
            WeightRecordAddForm form = new WeightRecordAddForm();
            form.MaterialList = m_MaterialList;
            form.SupplierList = m_SupplierList;
            form.PlaceList = m_PlaceList;
            form.DirectionList = m_DirectionList;
            if (form.ShowDialog() != DialogResult.OK)
                return;
            WeightRecordInfo recordInfo = form.CurrentRecordInfo;
            recordInfo.FirstWeightman = adminForm.User.employeeName;
            recordInfo.FirstWeightTime = DateTime.Now;
            recordInfo.LastWeightman = adminForm.User.employeeName;
            recordInfo.LastWeightTime = DateTime.Now;

            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("carCode", recordInfo.CarCode);
            dic.Add("materialCode", recordInfo.MaterialCode);
            dic.Add("materialName", recordInfo.MaterialName);
            dic.Add("supplierCode", recordInfo.SupplierCode);
            dic.Add("supplierName", recordInfo.SupplierName);
            dic.Add("placeCode", recordInfo.PlaceCode);
            dic.Add("placeName", recordInfo.PlaceName);
            dic.Add("directionCode", recordInfo.DirectionCode);
            dic.Add("directionName", recordInfo.DirectionName);
            dic.Add("receiveCode", recordInfo.ReceiveCode);
            dic.Add("receive", recordInfo.ReceiveName);
            dic.Add("tempWeight", recordInfo.TempWeight);
            dic.Add("grossWeight", recordInfo.GrossWeight);
            dic.Add("tareWeight", recordInfo.TareWeight);
            dic.Add("buckleWeight", recordInfo.BuckleWeight);
            dic.Add("buckleReasons", recordInfo.BuckleReasons);
            dic.Add("netWeight", recordInfo.NetWeight);
            dic.Add("firstWeightTime", recordInfo.FirstWeightTime.ToString("yyyy-MM-dd HH:mm:ss"));
            dic.Add("firstWeightMan", recordInfo.FirstWeightman);
            dic.Add("lastWeightTime", recordInfo.LastWeightTime.ToString("yyyy-MM-dd HH:mm:ss"));
            dic.Add("lastWeightMan", recordInfo.LastWeightman);  
            dic.Add("isRecord", 1);
            dic.Add("remark", recordInfo.Remark);
            dic.Add("isCompleted", 1);
            dic.Add("belongCorpId", int.Parse(ConfigurationManager.AppSettings["BelongCorpId"]));
            CGlobal.strSwapJsonData = JsonConvert.SerializeObject(dic);
            try
            {
                long systemId = ServerCommonHelper.SaveWeightRecords(adminForm.User.userame, adminForm.User.password);
                if (systemId == -1)
                {
                    MessageBox.Show("非采购物资数据补录失败，详细信息请参考日志文件!");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("非采购物资数据补录异常：" + ex.Message);
                LogHelper.error("非采购物资数据补录异常：" + ex.Message);
                return;
            } 
            Search();
        }

        //修改毛重
        private void btnModifyGross_Click(object sender, EventArgs e)
        {
            if (GV_loadInfos.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择数据!");
                return;
            }
            //若以上处的数据修改数据需联网状态
            DataGridViewRow selectedRows = GV_loadInfos.SelectedRows[0];
            long id = long.Parse(selectedRows.Cells["SystemIdColumn"].Value.ToString());
            string carCode = selectedRows.Cells["CarCodeColumn"].Value.ToString();
            int grossWeight = (int)decimal.Parse(selectedRows.Cells["GrossWeightColumn"].Value.ToString());
            int tareWeight = (int)decimal.Parse(selectedRows.Cells["TareWeightColumn"].Value.ToString());
            int netWeight = (int)decimal.Parse(selectedRows.Cells["NetWeightColumn"].Value.ToString());
            if (netWeight <= 0)
            {
                MessageBox.Show("毛重未确定，不能修改！");
                return;
            }

            decimal newGrossWeight = 0;
            //管理员权限进行修改
            AdminConfirmForm adminForm = new AdminConfirmForm();
            if (adminForm.ShowDialog() != DialogResult.OK)
                return;
            WeightModifyForm form = new WeightModifyForm(WeightModifyType.Gross);
            form.CarCode = carCode;
            form.OriginWeight = grossWeight;
            if (form.ShowDialog() != DialogResult.OK)
                return;
            newGrossWeight = form.NewWeight;
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("id", id);
            dic.Add("grossWeight", newGrossWeight);
            if (netWeight > 0)
            {
                decimal newNetWeight = newGrossWeight - tareWeight;
                dic.Add("netWeight", newNetWeight);
            }
            CGlobal.strSwapJsonData = JsonConvert.SerializeObject(dic);
            try
            {
                long systemId = ServerCommonHelper.SaveWeightRecords(adminForm.User.userame, adminForm.User.password);
                if (systemId == -1)
                {
                    MessageBox.Show("修改毛重失败，详细信息请参考日志文件!");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("修改毛重异常：" + ex.Message);
                LogHelper.error("修改毛重异常：" + ex.Message);
                return;
            }
            MessageBox.Show("修改毛重成功!");
            Search();
        }

        //修改皮重
        private void btnModifyTare_Click(object sender, EventArgs e)
        {
            if (GV_loadInfos.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择数据!");
                return;
            }
            //若以上处的数据修改数据需联网状态
            DataGridViewRow selectedRows = GV_loadInfos.SelectedRows[0];
            long id = long.Parse(selectedRows.Cells["SystemIdColumn"].Value.ToString());
            string carCode = selectedRows.Cells["CarCodeColumn"].Value.ToString();
            int grossWeight = (int)decimal.Parse(selectedRows.Cells["GrossWeightColumn"].Value.ToString());
            int tareWeight = (int)decimal.Parse(selectedRows.Cells["TareWeightColumn"].Value.ToString());
            int netWeight = (int)decimal.Parse(selectedRows.Cells["NetWeightColumn"].Value.ToString());
            if (netWeight <= 0)
            {
                MessageBox.Show("皮重未确定，不能修改！");
                return;
            }
            decimal newTareWeight = 0;
            //管理员权限进行修改
            AdminConfirmForm adminForm = new AdminConfirmForm();
            if (adminForm.ShowDialog() != DialogResult.OK)
                return;
            WeightModifyForm form = new WeightModifyForm(WeightModifyType.Tare);
            form.CarCode = carCode;
            form.OriginWeight = tareWeight;
            if (form.ShowDialog() != DialogResult.OK)
                return;
            newTareWeight = form.NewWeight;
            decimal newNetWeight = grossWeight - newTareWeight;
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("id", id);
            dic.Add("tareWeight", newTareWeight);
            dic.Add("netWeight", newNetWeight);
            CGlobal.strSwapJsonData = JsonConvert.SerializeObject(dic);
            try
            {
                long systemId = ServerCommonHelper.SaveWeightRecords(adminForm.User.userame, adminForm.User.password);
                if (systemId == -1)
                {
                    MessageBox.Show("修改皮重失败，详细信息请参考日志文件!");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("修改皮重异常：" + ex.Message);
                LogHelper.error("修改皮重异常：" + ex.Message);
                return;
            }
            MessageBox.Show("修改皮重成功!");
            Search();
        }

        //修改扣杂
        private void btnModifyBuckleWeight_Click(object sender, EventArgs e)
        {
            if (GV_loadInfos.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择数据!");
                return;
            }
            //若以上处的数据修改数据需联网状态
            DataGridViewRow selectedRows = GV_loadInfos.SelectedRows[0];
            long id = long.Parse(selectedRows.Cells["SystemIdColumn"].Value.ToString());
            string carCode = selectedRows.Cells["CarCodeColumn"].Value.ToString();

            int buckleWeight = (int)decimal.Parse(selectedRows.Cells["BuckleWeightColumn"].Value.ToString());

            //管理员权限进行修改
            AdminConfirmForm adminForm = new AdminConfirmForm();
            if (adminForm.ShowDialog() != DialogResult.OK)
                return;

            decimal newBuckleWeight = 0;

            WeightModifyForm form = new WeightModifyForm(WeightModifyType.Buckle);
            form.CarCode = carCode;
            form.OriginWeight = buckleWeight;
            if (form.ShowDialog() != DialogResult.OK)
                return;
            newBuckleWeight = form.NewWeight;
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("id", id);
            dic.Add("buckleWeight", newBuckleWeight);
            CGlobal.strSwapJsonData = JsonConvert.SerializeObject(dic);
            try
            {
                long systemId = ServerCommonHelper.SaveWeightRecords(adminForm.User.userame, adminForm.User.password);
                if (systemId == -1)
                {
                    MessageBox.Show("修改扣杂失败，详细信息请参考日志文件!");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("修改扣杂异常：" + ex.Message);
                LogHelper.error("修改扣杂异常：" + ex.Message);
                return;
            }
            MessageBox.Show("修改扣杂成功!");
            Search();
        }

        private void btnModifyCarCode_Click(object sender, EventArgs e)
        {
            if (GV_loadInfos.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择数据!");
                return;
            }
            //若以上处的数据修改数据需联网状态
            DataGridViewRow selectedRows = GV_loadInfos.SelectedRows[0];
            long id = long.Parse(selectedRows.Cells["SystemIdColumn"].Value.ToString());
            string carCode = selectedRows.Cells["CarCodeColumn"].Value.ToString();
            int netWeight = (int)decimal.Parse(selectedRows.Cells["NetWeightColumn"].Value.ToString());
            string newCarCode = "";

            //管理员权限进行修改
            AdminConfirmForm adminForm = new AdminConfirmForm();
            if (adminForm.ShowDialog() != DialogResult.OK)
                return;
            CarCodeModifyForm form = new CarCodeModifyForm();
            form.CarCode = carCode;
            if (form.ShowDialog() != DialogResult.OK)
                return;
            newCarCode = form.CarCode;

            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("id", id);
            dic.Add("carCode", newCarCode);
            CGlobal.strSwapJsonData = JsonConvert.SerializeObject(dic);
            try
            {
                long systemId = ServerCommonHelper.SaveWeightRecords(adminForm.User.userame, adminForm.User.password);
                if (systemId == -1)
                {
                    MessageBox.Show("修改车牌号失败，详细信息请参考日志文件!");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("修改车牌号异常：" + ex.Message);
                LogHelper.error("修改车牌号异常：" + ex.Message);
                return;
            }
            //最后再修改本地数据
            if (netWeight <= 0)
            {
                try
                {
                    string sql = "update WeightRecords set CarCode = '" + newCarCode + "' where SystemId = " + id;
                    if (!CommonHelper.DoOpreation(sql))
                    {
                        MessageBox.Show("修改车牌号失败,详细信息请参考日志文件!");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.error("修改车牌号异常:" + ex.ToString());
                    MessageBox.Show("修改车牌号异常,详细信息请参考日志文件!");
                    return;
                }
            }
            MessageBox.Show("修改车牌号成功!");
            Search();
        }

        //导出Excel
        private void btnExportExcel_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "Export Excel File To";
            DialogResult dr = saveFileDialog.ShowDialog();

            if (dr == DialogResult.Cancel)
                return;
            Stream myStream = saveFileDialog.OpenFile();

            if (CommonHelper.ExportExcel(myStream, this.GV_loadInfos))
                MessageBox.Show("导出Excel成功！");
            else
                MessageBox.Show("导出Excel失败！");
        }

        private void btnReprint_Click(object sender, EventArgs e)
        {
            //本地待上传数据磅单补打只有完结且修改本地的
            if (GV_loadInfos.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先选择数据!");
                return;
            }
            WeightRecordInfo weightRecordInfo = ServerCommonHelper.ConvertWeightRecordInfoByRow(GV_loadInfos.SelectedRows[0]);
            if (!weightRecordInfo.IsCompleted)
            {
                MessageBox.Show(this, "称重尚未完结,无法打印！");
                return;
            }
            try
            {
                using (LTCardAPIServiceClient client = new LTCardAPIServiceClient())
                {
                    bool isOnline = ServerCommonHelper.IsWebServiceAvaiable(client.Endpoint.Address.Uri);
                    AdminConfirmForm adminForm = new AdminConfirmForm();
                    adminForm.IsOnline = isOnline;
                    adminForm.UserType = "管理员";
                    if (adminForm.ShowDialog() != DialogResult.OK)
                        return;

                    List<WeightRecordInfo> list = new List<WeightRecordInfo>();
                    Dictionary<string, object> dic = new Dictionary<string, object>();
                    dic.Add("id", weightRecordInfo.SystemId);
                    CGlobal.strSwapJsonData = JsonConvert.SerializeObject(dic);
                    try
                    {
                        list = ServerCommonHelper.GetWeightRecordsByCondition(adminForm.User.userame, adminForm.User.password);
                        if (list.Count == 0)
                        {
                            MessageBox.Show(this, "未获取到ID：" + weightRecordInfo.SystemId + "过磅记录！");
                            return;
                        }
                        LogHelper.info("磅单补打根据id:" + weightRecordInfo.SystemId
                            + "查询的数据个数：" + list.Count.ToString() + "车牌号：" + list[0].CarCode);
                        WeightRecordInfo printInfo = list[0];
                        if (!CommonHelper.Print(printInfo, adminForm.User.employeeName))
                        {
                            MessageBox.Show(this, "磅单补打失败，详细信息请参考日志文件！");
                            return;
                        }
                        MessageBox.Show("磅单补打成功！");

                        dic = new Dictionary<string, object>();
                        dic.Add("id", weightRecordInfo.SystemId);
                        dic.Add("isPrinted", 1);
                        CGlobal.strSwapJsonData = JsonConvert.SerializeObject(dic);
                        try
                        {
                            long systemId = ServerCommonHelper.SaveWeightRecords(adminForm.User.userame, adminForm.User.password);
                            if (systemId == -1)
                            {
                                MessageBox.Show("磅单补打修改打印字段失败，详细信息请参考日志文件！");
                                return;
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("磅单补打修改打印字段异常：" + ex.Message);
                            LogHelper.error("磅单补打修改打印字段异常：" + ex.Message);
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, "获取到ID：" + weightRecordInfo.SystemId + "过磅记录异常：" + ex.Message);
                        LogHelper.error("获取到ID：" + weightRecordInfo.SystemId + "过磅记录异常：" + ex.Message);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.error("磅单补打异常：" + ex.ToString());
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }
        #endregion

        #region 下拉框事件
        //选择的物料
        private void cmbMaterial_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbMaterial.SelectedItem == null || cmbMaterial.SelectedItem.ToString() == "")
              m_MaterialCode = "";
          else
              m_MaterialCode = ((DataInfo)cmbMaterial.SelectedItem).Id;
        }

        //选择的供应商
        private void cmbSupplier_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSupplier.SelectedItem == null || cmbSupplier.SelectedItem.ToString() == "")
                m_SupplierCode= "";
            else
                m_SupplierCode = ((DataInfo)cmbSupplier.SelectedItem).Id;
        }

        private void cmbPlace_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbPlace.SelectedItem == null || cmbPlace.SelectedItem.ToString() == "")
                m_PlaceCode = "";
            else
                m_PlaceCode = ((DataInfo)cmbPlace.SelectedItem).Id;
        }

        private void cmbDirection_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbDirection.SelectedItem == null || cmbDirection.SelectedItem.ToString() == "")
                m_DirectionCode = "";
            else
                m_DirectionCode = ((DataInfo)cmbDirection.SelectedItem).Id;
        }

        //选择打印状态
        private void cmbPrinted_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbPrinted.SelectedItem == null || cmbPrinted.SelectedItem.ToString() == "")
            {
                cmbPrinted.SelectedIndex = 0;
                m_Printed = 0;
            }
            else
            {
                string id = ((DataInfo)cmbPrinted.SelectedItem).Id;
                m_Printed = Convert.ToInt32(id);
            }
        }

        private void cmbIsReturn_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbIsReturn.SelectedItem == null || cmbIsReturn.SelectedItem.ToString() == "")
            {
                cmbIsReturn.SelectedIndex = 0;
                m_Record = 0;
            }
            else
            {
                string id = ((DataInfo)cmbIsReturn.SelectedItem).Id;
                m_Record = Convert.ToInt32(id);
            }
        }

        //选择的状态
        private void cmbStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbStatus.SelectedItem == null || cmbStatus.SelectedItem.ToString() == "")
            {
                cmbStatus.SelectedIndex = 0;
                m_Status = 0;
            }
            else
            {
                string id = ((DataInfo)cmbStatus.SelectedItem).Id;
                m_Status = Convert.ToInt32(id);
            }
        }
        #endregion

        #region 查询
        private void Search()
        {
            Dictionary<string, object> dic = CreateSearchSql();
            try
            {
                CGlobal.strSwapJsonData = JsonConvert.SerializeObject(dic);
                List<WeightRecordInfo> list = ServerCommonHelper.GetWeightRecordsByCondition(m_CurrentUser, m_Password);
                m_BindDT.Rows.Clear();
                if (list == null || list.Count == 0)
                {
                    this.txtRecordNum.Text = "0";
                    this.txtGrossTotal.Text = "0";
                    this.txtTareTotal.Text = "0";
                    this.txtNetTotal.Text = "0";
                    this.txtBuckleTotal.Text = "0";
                    return;
                }
                this.GV_loadInfos.DataSource = m_BindDT;
                BindData(list);
            }
            catch (Exception ex)
            {
                LogHelper.error("查询异常：" + ex.ToString());
                MessageBox.Show("查询异常,详细信息请参考日志文件!");
            }
        }

        private Dictionary<string, object> CreateSearchSql()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            if (chkIsUseFirst.Checked)
            {
                DateTime startTime = this.fromFirstTime.DateTime;
                DateTime endTime = this.toFirstTime.DateTime;
                dic.Add("fromFirstWeightTime", startTime.ToString("yyyy-MM-dd HH:mm:ss"));
                dic.Add("toFirstWeightTime", endTime.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            if (chkIsUseSecond.Checked)
            {
                DateTime startTime = this.fromLastTime.DateTime;
                DateTime endTime = this.toLastTime.DateTime;
                dic.Add("fromLastWeightTime", startTime.ToString("yyyy-MM-dd HH:mm:ss"));
                dic.Add("toLastWeightTime", endTime.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            if (!string.IsNullOrEmpty(txtCarCode.Text.Trim()))
            {
                dic.Add("carCode", txtCarCode.Text.Trim());
            }
            if (!string.IsNullOrEmpty(m_MaterialCode))
            {
                dic.Add("materialCode", m_MaterialCode);
            }
            if (!string.IsNullOrEmpty(m_SupplierCode))
            {
                dic.Add("supplierCode", m_SupplierCode);
            }
            if (!string.IsNullOrEmpty(m_PlaceCode))
            {
                dic.Add("placeCode", m_PlaceCode);
            }
            if (!string.IsNullOrEmpty(m_DirectionCode))
            {
                dic.Add("directionCode", m_DirectionCode);
            }
            if (m_Printed != (int)PrintedEnum.All)
            {
                if (m_Printed == (int)PrintedEnum.Printed)
                    dic.Add("isPrinted", 1);
                else if (m_Printed == (int)PrintedEnum.UnPrinted)
                    dic.Add("isPrinted", 0);
            }
            if (m_Record != (int)RecordEnum.All)
            {
                if (m_Record == (int)RecordEnum.Record)
                    dic.Add("isRecord", 1);
                else if (m_Record == (int)RecordEnum.UnRecord)
                    dic.Add("isRecord", 0);
            }
            if (m_Status != (int)StatusEnum.All)
            {
                if (m_Status == (int)StatusEnum.Completed)
                    dic.Add("isCompleted", 1);
                else if (m_Status == (int)StatusEnum.UnCompleted)
                    dic.Add("isCompleted", 0);
            }
            return dic;
        }

        //绑定列表
        private void BindData(List<WeightRecordInfo> list)
        {
            long systemId;
            string carCode = "";
            string materialCode = "";
            string material = "";
            string supplierCode = "";
            string supplier = "";
            string placeCode = "";
            string place = "";
            string directionCode = "";
            string direction = "";
            string receiveCode = "";
            string receive = "";
            decimal tempWeight = 0;
            decimal grossWeight = 0;
            decimal tareWeight = 0;
            decimal buckleWeight = 0;
            string buckleReasons = "";
            decimal netWeight = 0;
            DateTime firstWeightTime;
            string firstWeightMan = "";
            DateTime lastWeightTime;
            string lastWeightMan = "";
            string status = "";
            string printed = "";
            string isRecord = "";
            string remark = "";

            int recordNum = 0;
            decimal grossWeightTotal = 0;
            decimal tareWeightTotal = 0;
            decimal buckleWeightTotal = 0;
            decimal netWeightTotal = 0;
            try
            {
                foreach (WeightRecordInfo recordInfo in list)
                {
                    systemId = recordInfo.SystemId;
                    carCode = recordInfo.CarCode;
                    materialCode = recordInfo.MaterialCode;
                    material = recordInfo.MaterialName;
                    supplierCode = recordInfo.SupplierCode;
                    supplier = recordInfo.SupplierName;
                    placeCode = recordInfo.PlaceCode;
                    place = recordInfo.PlaceName;
                    directionCode = recordInfo.DirectionCode;
                    direction = recordInfo.DirectionName;
                    receiveCode = recordInfo.ReceiveCode;
                    receive = recordInfo.ReceiveName;

                    tempWeight = recordInfo.TempWeight;
                    grossWeight = recordInfo.GrossWeight;
                    tareWeight = recordInfo.TareWeight;
                    buckleWeight = recordInfo.BuckleWeight;
                    buckleReasons = recordInfo.BuckleReasons;

                    netWeight = grossWeight - tareWeight - buckleWeight;
                    firstWeightTime = recordInfo.FirstWeightTime;
                    firstWeightMan = recordInfo.FirstWeightman;
                    lastWeightTime = recordInfo.LastWeightTime;
                    lastWeightMan = recordInfo.LastWeightman;
                    printed = recordInfo.IsPrinted == true ? "已打印" : "未打印";
                    status = recordInfo.IsCompleted == true ? "完结" : "未完结";
                    isRecord = recordInfo.IsRecord == true ? "是" : "否";

                    m_BindDT.Rows.Add(systemId, carCode, materialCode, material, supplierCode, supplier, placeCode, place,
                        directionCode, direction, receiveCode, receive, tempWeight.ToString("0"), grossWeight.ToString("0"), tareWeight.ToString("0"),
                        buckleWeight.ToString("0"), buckleReasons, netWeight.ToString("0"),
                        firstWeightTime, firstWeightMan, lastWeightTime, lastWeightMan, status, printed, isRecord, remark);

                    recordNum++;
                    grossWeightTotal += grossWeight;
                    tareWeightTotal += tareWeight;
                    buckleWeightTotal += buckleWeight;
                    netWeightTotal += netWeight;
                }
                this.GV_loadInfos.DataSource = m_BindDT;

                this.txtRecordNum.Text = recordNum.ToString();
                this.txtGrossTotal.Text = (grossWeightTotal / 1000).ToString();
                this.txtTareTotal.Text = (tareWeightTotal / 1000).ToString();
                this.txtNetTotal.Text = (netWeightTotal / 1000).ToString();
                this.txtBuckleTotal.Text = (buckleWeightTotal / 1000).ToString();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
        #endregion

        //行号
        private void GV_loadInfos_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y,
                GV_loadInfos.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
            GV_loadInfos.RowHeadersDefaultCellStyle.Font, rectangle,
            GV_loadInfos.RowHeadersDefaultCellStyle.ForeColor,
            TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
    }
}
